package com.cmsky.open.web.controller;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.cmsky.open.core.util.JsonUtils;
import com.cmsky.open.user.model.UserInfo;
import com.cmsky.open.user.service.UserLoginService;
/**
 * 商城相关
 * @author jandyfish
 *
 */
@Controller
@RequestMapping("/g")
public class IndexController {
	private UserLoginService userLoginService;
	
	public void setUserLoginService(UserLoginService userLoginService) {
		this.userLoginService = userLoginService;
	}

	/** 
	 * 进入商城首页
	 **/
	@RequestMapping("/index")
	public ModelAndView index(HttpServletRequest request,HttpServletResponse response) throws Exception {
		return new ModelAndView("forward:/food/i/index.do");
	}
	
	/**
	 * 进入登录页面
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/toLg")
	public ModelAndView toLg(HttpServletRequest request,HttpServletResponse response) throws Exception {
		ModelAndView view = null;
		UserInfo user = userLoginService.getLoginedUser(request, response);
		if(null!=user){
			view = this.index(request, response);
		}else{
			view = new ModelAndView("/g/login");
		}
		return view;
	}
	
	/**
	 * 同步登录
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/login")
	public ModelAndView login(HttpServletRequest request,HttpServletResponse response) throws Exception {
		ModelAndView view = null;
		UserInfo user = userLoginService.getLoginedUser(request, response);
		if(null==user){
			String email = request.getParameter("username");
			String passwd = request.getParameter("pwd");
			user = userLoginService.lgIn(request, response, email, passwd);
		}
		if(null!=user){
			view = new ModelAndView("redirect:/");
		}else{
			view = new ModelAndView("/g/login");
			view.addObject("errorMsg", "登录错误,邮箱和密码不匹配!");
		}
		return view;
	}
	
	@RequestMapping("/lgOut")
	public ModelAndView lgOut(HttpServletRequest request,HttpServletResponse response) throws Exception{
		this.userLoginService.lgOut(request, response);
		return new ModelAndView("redirect:/");
	}
	
	@ResponseBody
	@RequestMapping("/getLgUser")
	public String getLgUser(HttpServletRequest request,HttpServletResponse response)throws Exception {
		UserInfo user = userLoginService.getLoginedUser(request, response);
		if(null!=user){
			return JsonUtils.jsonFromObject(user);
		}else{
			return null;
		}
	}
}
